package com.kx.center.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.entity.Stockin;
import com.kx.center.entity.StockinDetail;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.entity.query.QueryStockin;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.service.StockinService;
import com.kx.center.util.DateUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;

@Controller
@RequestMapping("/stockin")
public class StockinController {

	@Autowired
	StockinService service;

	@RequestMapping(value = "list/{storeId}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String list(HttpServletRequest request, @PathVariable("storeId") Integer storeId) throws Exception {
		
		Integer page, pageSize, status;
		Date from = null, to = null;
		
		QueryStockin query = new QueryStockin();

		String storeIdStr = request.getParameter("store");
		String fromStr = request.getParameter("from");
		String toStr = request.getParameter("to");
		
		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");
		
		status = NumberUtils.toInt(request.getParameter("status"));
		page = NumberUtils.toInt(request.getParameter("page"));
		pageSize = NumberUtils.toInt(request.getParameter("pageSize"));
		
		if(DateUtil.isDate(fromStr))
			from = DateUtils.parseDate(fromStr, "yyyy-MM-dd");

		if(DateUtil.isDate(toStr))
			to = DateUtils.parseDate(toStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
		
		if(storeId <= 0)
			storeId = NumberUtils.toInt(storeIdStr);
		
		if(StringUtils.isBlank(sortBy))
			sortBy = "addtime";
		
		if(StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		query.setFrom(from);
		query.setTo(to);
		query.setStoreId(storeId);
		query.setStatus(status);
		query.setPage(page);
		query.setPageSize(pageSize);
		query.setSortBy(sortBy);
		query.setSortMethod(sortMethod);

		if (storeId > 0) {
			query.setStoreId(storeId);
		}
		
		query.setSortBy("addtime");
		query.setSortMethod("desc");

		QueryResult result = service.queryStockin(query);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	@RequestMapping(value = "detail/{sid}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String stockin_detail(HttpServletRequest request, @PathVariable("sid") Integer sid) throws Exception {

		if (sid != null && sid > 0) {
			List<StockinDetail> list = service.findStockinDetailBySId(sid);

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("data", list);
			return Response.success(map);
		} else {
			return Response.error(MessageCode.NO_DATA);
		}
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "save", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request) {

		String sidStr = request.getParameter("sid");

		String json = request.getParameter("data");

		Integer sid = 0;

		if (StringUtils.isBlank(json)) {
			return Response.error(MessageCode.JSON_WRONG);
		}

		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

		try {
			data = (ArrayList<HashMap<String, Object>>) JSONParser.parse(json, data.getClass());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(MessageCode.JSON_WRONG);
		}

		if (sidStr != null && NumberUtils.isDigits(sidStr)) {
			sid = NumberUtils.toInt(sidStr);
		}

		if (sid <= 0)
			return Response.error(MessageCode.STOCKIN_ID_WRONG);

		Stockin entity = service.findStockinById(sid);

		if (entity == null || entity.getStatus() != 1) {
			return Response.error(MessageCode.INVALID_OPERATOR);
		}

		service.saveStockin(entity, data);

		return Response.success("入库单数据提交成功");
	}
	
	@RequestMapping(value = "{sid}/confirm", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String confirm(HttpServletRequest request, @PathVariable("sid") Integer sid) {
		if (sid <= 0) {
			return Response.error(MessageCode.REQUEST_ERROR);
		} else {
			Stockin entity = service.findStockinById(sid);

			if (entity == null)
				return Response.error(MessageCode.STOCKIN_ID_WRONG);
			else {
				if (entity.getStatus() != 1)
					return Response.error(MessageCode.OPERATOR_FAIL);
				else {
					entity.setStatus(2);
					service.confirm(entity);
					return Response.success();
				}
			}
		}
	}
}
